package com.ruoyi.common.utils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;

import org.apache.commons.lang3.time.DateFormatUtils;

/**
 * 时间工具类
 *
 * @author ruoyi
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算相差天数
     */
    public static int differentDaysByMillisecond(Date date1, Date date2) {
        return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
    }

    /**
     * 计算时间差
     *
     * @param endDate   最后时间
     * @param startTime 开始时间
     * @return 时间差（天/小时/分钟）
     */
    public static String timeDistance(Date endDate, Date startTime) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - startTime.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor) {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor) {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 获取月最后一天日期
     *
     * @param date
     * @return
     */
    public static String getYearMonthLastDay(String date) {
        SimpleDateFormat ym = new SimpleDateFormat("yyyy-MM");
        Calendar c = Calendar.getInstance();
        try {
            c.setTime(ym.parse(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date + "-" + c.getActualMaximum(Calendar.DATE);
    }

    /**
     * 获取两个日期之间的所有月份 (年月)
     */
    public static List<String> getMonthBetweenDate(String startTime, String endTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        // 声明保存日期集合
        List<String> list = new ArrayList<>();
        try {
            // 转化成日期类型
            Date startDate = sdf.parse(startTime);
            Date endDate = sdf.parse(endTime);

            //用Calendar 进行日期比较判断
            Calendar calendar = Calendar.getInstance();
            while (startDate.getTime() <= endDate.getTime()) {

                // 把日期添加到集合
                list.add(sdf.format(startDate));

                // 设置日期
                calendar.setTime(startDate);

                //把月数增加 1
                calendar.add(Calendar.MONTH, 1);

                // 获取增加后的日期
                startDate = calendar.getTime();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 获取两个日期之间的所有年份
     */
    public static List<String> getYears(String year1, String year2) {
        // 声明保存日期集合
        List<String> list = new ArrayList<String>();
        int year1_ = Integer.valueOf(year1);
        int year2_ = Integer.valueOf(year2);
        for (int i = year1_; i <= year2_; i++) {
            list.add(String.valueOf(i));
        }
        return list;
    }

    /**
     * 获取指定时间年份
     **/
    public static Integer getYear(String datatime, String type) {
        SimpleDateFormat sdf = new SimpleDateFormat(type);
        Calendar calendar = Calendar.getInstance();
        Date parse = null;
        try {
            parse = sdf.parse(datatime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        calendar.setTime(parse);
        int year = calendar.get(Calendar.YEAR);
        return year;
    }

    /**
     * 根据时间或者月份
     **/
    public static String MONTH(String endTime, String type) {
        SimpleDateFormat df = new SimpleDateFormat(type);
        Calendar ca = Calendar.getInstance();
        Date parse = null;
        try {
            parse = df.parse(endTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        ca.setTime(parse);
        String month = "";
        int months = ca.get(Calendar.MONTH) + 1; // Calendar.MONTH 的取值范围是 0-11，需要加1
        // System.out.println("当前月份：" + months);
        //int MONTH = ca.get(Calendar.MONTH) + 1;
        if (months < 10) {
            month = "0" + String.valueOf(months);
        } else {
            month = String.valueOf(months);
        }
        return month;
    }

    /**
     * 根据传入的时间查询同比和环比
     *
     * @Param [ksdate 开始时间, jsdata 结束时间, typeData 数据类型]
     **/
    public static Map<String, Object> OnTheSameMonthRatio(String ksdate, String jsdata, String typeData) {
        Map<String, Object> map = new HashMap<>();
        String tbksData = null;
        String tbjsData = null;
        String hbksData = null;
        String hbjsData = null;
        // 获取当前日期
        //将时间格式化成yyyy-MM-dd HH:mm:ss的格式
        SimpleDateFormat format = new SimpleDateFormat(typeData);
        Calendar calendar = Calendar.getInstance();
        try {
            //获取同比时间 上一年
            Date parse = format.parse(ksdate);
            Date parse1 = format.parse(jsdata);
            calendar.setTime(parse);
            calendar.add(Calendar.YEAR, -1);
            tbksData = format.format(calendar.getTime());
            calendar.setTime(parse1);
            calendar.add(Calendar.YEAR, -1);
            tbjsData = format.format(calendar.getTime());
            //获取环比时间 上一月
            calendar.setTime(parse);
            calendar.add(Calendar.MONTH, -1);
            hbksData = format.format(calendar.getTime());
            calendar.setTime(parse1);
            calendar.add(Calendar.MONTH, -1);
            hbjsData = format.format(calendar.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        map.put("tbksData", tbksData);
        map.put("tbjsData", tbjsData);
        map.put("hbksData", hbksData);
        map.put("hbjsData", hbjsData);

        return map;
    }

    public static List<String> getMonthall(String year1, String year2) {
        List<String> list = new ArrayList<String>();
        try {
            Date startDate = new SimpleDateFormat("yyyy-MM").parse(year1);
            Date endDate = new SimpleDateFormat("yyyy-MM").parse(year2);

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startDate);
            // 获取开始年份和开始月份
            int startYear = calendar.get(Calendar.YEAR);
            int startMonth = calendar.get(Calendar.MONTH);
            // 获取结束年份和结束月份
            calendar.setTime(endDate);
            int endYear = calendar.get(Calendar.YEAR);
            int endMonth = calendar.get(Calendar.MONTH);
            //

            for (int i = startYear; i <= endYear; i++) {
                String date = "";
                if (startYear == endYear) {
                    for (int j = startMonth; j <= endMonth; j++) {
                        if (j < 9) {
                            date = i + "-0" + (j + 1);
                        } else {
                            date = i + "-" + (j + 1);
                        }
                        list.add(date);
                    }

                } else {
                    if (i == startYear) {
                        for (int j = startMonth; j < 12; j++) {
                            if (j < 9) {
                                date = i + "-0" + (j + 1);
                            } else {
                                date = i + "-" + (j + 1);
                            }
                            list.add(date);
                        }
                    } else if (i == endYear) {
                        for (int j = 0; j <= endMonth; j++) {
                            if (j < 9) {
                                date = i + "-0" + (j + 1);
                            } else {
                                date = i + "-" + (j + 1);
                            }
                            list.add(date);
                        }
                    } else {
                        for (int j = 0; j < 12; j++) {
                            if (j < 9) {
                                date = i + "-0" + (j + 1);
                            } else {
                                date = i + "-" + (j + 1);
                            }
                            list.add(date);
                        }
                    }

                }

            }

            // 所有的月份已经准备好
            //System.out.println(list);
            for (int i = 0; i < list.size(); i++) {
                System.out.println(list.get(i));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * @param date 时间
     * @return 获取某个时间本月第一天
     */
    public static String getFirstDayOfMonth(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        return (new SimpleDateFormat(YYYY_MM_DD)).format(cal.getTime());
    }

    /**
     * 获取某月最后一天
     *
     * @param date
     * @return
     */
    public static String getLastDayOfMonth(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        return sdf.format(cal.getTime());
    }

    /**
     * @title getFirstDayOfMonth
     * @description  返回某年的第一天
     * @param date
     * @return java.lang.String
     */
    public static String getFirstDayOfYear(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.DAY_OF_YEAR,1);
        return (new SimpleDateFormat(YYYY_MM_DD)).format(calendar.getTime());
    }
    /**
     * @title getLastDayOfMonth
     * @description  返回某年的最后一天
     * @param date
     * @return java.lang.String
     */
    public static String getLastDayOfYear(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.DAY_OF_YEAR, cal.getActualMaximum(Calendar.DAY_OF_YEAR));
        return sdf.format(cal.getTime());
    }


    public static void main(String[] args) {
        System.out.println(getFirstDayOfYear(new Date()));
        System.out.println(getLastDayOfYear(new Date()));
    }

    public static List<String> getHourBetweenDatetype(String startTime, String endTime, String type) {
        SimpleDateFormat sdf = new SimpleDateFormat(type);
        Instant ksinstant = null;
        Instant jsinstant = null;
        try {
            Date parseparse = sdf.parse(startTime);
            Date eparse = sdf.parse(endTime);
            // @since 1.8
            ksinstant = parseparse.toInstant();
            jsinstant = eparse.toInstant();
        } catch (ParseException e) {
            e.printStackTrace();
        }

// 设置时区
        ZoneOffset zoneOffset = ZoneOffset.of("+8");
// 方式二：使用 LocalDateTime 的 ofEpochSecond 进行转换
        LocalDateTime startTimes = LocalDateTime.ofEpochSecond(ksinstant.getEpochSecond(), ksinstant.getNano(), zoneOffset);
        LocalDateTime endTimes = LocalDateTime.ofEpochSecond(jsinstant.getEpochSecond(), jsinstant.getNano(), zoneOffset);
        List<String> list = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime current = startTimes;
        while (current.isBefore(endTimes) || current.equals(endTimes)) {
            list.add(current.format(formatter));
            current = current.plusHours(1);
        }
        return list;
    }


    /**
     * 获取2个日期之间的所有日数据（）
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public static List<String> getdayBetweenDate(String startTime, String endTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<String> dateList = new ArrayList<String>();
        try {
            Date dateOne = sdf.parse(startTime);
            Date dateTwo = sdf.parse(endTime);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(dateOne);
            dateList.add(startTime);
            while (dateTwo.after(calendar.getTime())) {
                calendar.add(Calendar.DAY_OF_MONTH, 1);
                dateList.add(sdf.format(calendar.getTime()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dateList;
    }

    /**
     * 将date类型转为String类型
     *
     * @param date 时间
     * @param type 格式
     * @return
     */
    public static String dateFormat(Date date, String type) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(type);
        return sdf.format(date);
    }

    /**
     * @param date  日期时间
     * @param count 添加的天数
     * @return 返回计算后的日期时间
     */
    public static Date addDay(Date date, int count) {
        return new Date(date.getTime() + 0x5265c00L * (long) count);
    }

    /**
     * 获取月份
     **/
    public static Integer getmoon(String datatime, String type) {
        SimpleDateFormat sdf = new SimpleDateFormat(type);
        Calendar calendar = Calendar.getInstance();
        Date parse = null;
        try {
            parse = sdf.parse(datatime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        calendar.setTime(parse);
        int year = calendar.get(Calendar.MONTH);
        return year + 1;
    }

    /**
     * @param year 年份
     * @return 返回某年的第一天
     */
    public static Date getFirstDayOfYear(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        Date currYearFirst = calendar.getTime();
        return currYearFirst;
    }

    /**
     * @param year 年份
     * @return 返回某年最后一天
     */
    public static Date getLastDayOfYear(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        calendar.roll(Calendar.DAY_OF_YEAR, -1);
        Date currYearLast = calendar.getTime();
        return currYearLast;
    }

    public static List<String> getLast12Months(String daymonitorTime) {
        List<String> months = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Date parse = null;
        try {
            parse = sdf.parse(daymonitorTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar currentDate = Calendar.getInstance();
        currentDate.setTime(parse);
        for (int i = 0; i < 12; i++) {
            currentDate = (Calendar) currentDate.clone();
            if (i == 0) {

            } else {
                currentDate.add(Calendar.MONTH, -1);
            }
            Date time = currentDate.getTime();
            String format = sdf.format(time);
            boolean contains = months.contains(format);
            if (!months.contains(format)) {
                months.add(format);
            }

        }

        return months;
    }
}
